<?php

namespace Home\Controller;

use Home\Controller;

class IndexController extends BaseController
{

    public function index()
    {
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
          $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
        //echo "<pre>";print_r($result);
        $this->assign('loginuid', session('homeId'));
        if ($result['isggconfig'] == '2') {
            $result['uptype'] = '2';
        }
        if ($result['isggconfig']) {
            $config = M("Config")->find();
            $result['accesskey'] = $config['ggaccesskey'];
            $result['secretkey'] = $config['ggsecretkey'];
            $result['bucket'] = $config['ggbucket'];
            $result['domain'] = $config['ggdomain'];
            $result['classon'] = 'class = "active"';

            $this->result = $result;
            $Ipaddress = M("Ipaddress"); // 实例化User对象
            $data['ipaddr'] = get_client_ipaddress();
            $data['dtime'] = time();
            $data['tid'] = session('homeId');
            $Ipaddress->add($data);

            $list = M('list')->where("1=1")->order('id DESC')->limit('10')->select();
            $this->list = $list;
            $this->display();
        } else {
            $result['classon'] = 'class = "on"';
            $this->result = $result;
            if ($result['uptype'] == 1 && $result['accesskey'] == '' && $result['secretkey'] == '') {

                $this->success("当前为七牛上传，请设置七牛信息...", U('Member/jiekou'), 3);

            } else {
                $Ipaddress = M("Ipaddress"); // 实例化User对象
                $data['ipaddr'] = get_client_ipaddress();
                $data['dtime'] = time();
                $data['tid'] = session('homeId');
                $Ipaddress->add($data);

                $list = M('list')->where("1=1")->order('id DESC')->limit('10')->select();
                $this->list = $list;
                $this->display();
            }
        }


    }

    public function checkupid()
    {
        $id = trim(I("id"));
        $model = M("List");
        $where['id'] = $id;
        $where['fid'] = session('homeId');
        $this->info = $model->where($where)->find();
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
        //echo "<pre>";print_r($result);
        $this->assign('loginuid', session('homeId'));
        if ($result['isggconfig'] == '2') {
            $result['uptype'] = '2';
        }
        if ($result['isggconfig']) {
            $config = M("Config")->find();
            $result['accesskey'] = $config['ggaccesskey'];
            $result['secretkey'] = $config['ggsecretkey'];
            $result['bucket'] = $config['ggbucket'];
            $result['domain'] = $config['ggdomain'];
            $result['classon'] = 'class = "active"';
            $this->result = $result;
            $Ipaddress = M("Ipaddress"); // 实例化User对象
            $data['ipaddr'] = get_client_ipaddress();
            $data['dtime'] = time();
            $data['tid'] = session('homeId');
            $Ipaddress->add($data);

            $list = M('list')->where("1=1")->order('id DESC')->limit('10')->select();
            $this->list = $list;
            $this->display();
        } else {
            $result['classon'] = 'class = "on"';
            $this->result = $result;
            if ($result['uptype'] == 1 && $result['accesskey'] == '' && $result['secretkey'] == '') {

                $this->success("当前为七牛上传，请设置七牛信息...", U('Member/jiekou'), 3);

            } else {
                $Ipaddress = M("Ipaddress"); // 实例化User对象
                $data['ipaddr'] = get_client_ipaddress();
                $data['dtime'] = time();
                $data['tid'] = session('homeId');
                $Ipaddress->add($data);

                $list = M('list')->where("1=1")->order('id DESC')->limit('10')->select();
                $this->list = $list;
                $this->display();
            }
        }

    }

    public function updateid()
    {
        if ($_POST) {
            $upid = trim(I('post.upid'));
            $id = trim(I('post.id'));

            $list = M('List');

            $where['id'] = $id;
            $where['fid'] = session('homeId');
            $info = $list->where($where)->find();
            if (empty($info)) {
                $this->error("请输入正确id");
            }

            $list->where(array('id' => $id))->setField('upid', $upid);
            $this->updateall($id, $upid);
            $this->success("升级成功");
        } else {
            $this->error("恶意提交");
        }
    }

    public function updateall($id, $upid)
    {
        $list = M('List');
        $where = array();
        $where['upid'] = $id;
        $where['fid'] = session('homeId');
        $info = $list->where($where)->find();
        if (isset($info['id']) && $info['id']) {
            $list->where(array('id' => $info['id']))->setField('upid', $upid);
            $this->updateall($info['id'], $upid);
        } else {
            return false;
        }
    }

    public function gettoken()
    {
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        if ($result['isggconfig'] == '1') {
            $config = M("Config")->find();
            $result['accesskey'] = $config['ggaccesskey'];
            $result['secretkey'] = $config['ggsecretkey'];
            $result['bucket'] = $config['ggbucket'];
            $result['domain'] = $config['ggdomain'];
        }
        // 初始化签权对象
        $auth = new \Qiniu\Auth(trim($result['accesskey']), trim($result['secretkey']));
        // 生成上传Token
        $token = $auth->uploadToken(trim($result['bucket']));
        //$arr = array('token'=>$token);
        echo $token;
    }

    public function userqn()
    {
        if (!empty($_POST)) {
            $ss = $_POST['ss'];

            $member = M('Member');
            $result = $member->where(array('id' => session('homeId')))->find();

            $uploadedsize = $_POST['iAppSize'] / 1024 / 1024;
            $member->where(array('id' => session('homeId')))->setInc('uploadedsize', round($uploadedsize, 2));

            $domain = trim($_POST['sDownLink']);
            $houzhui = trim($_POST['hext']);


            $model = M("List");
            $model->uptxt = $domain;
            $model->hslogo = $_POST['hslogo'];
            $model->qnname = $_POST['apkName'];
            $model->nickname = $_POST['happName'];
            $model->create_time = time();
            $model->zsize = $_POST['iAppSize'];
            $model->fid = session('homeId');
            $model->ext = $houzhui;
            $model->needmoney = '1';
            if(empty($ss)){
                if ($res = $model->add()) {
                    //处理该上传文件
                    $ctlist = array(
                        'ssl_server' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
                        'bundle_identifier' => $_POST['hpackageName'],
                        'title' => $_POST['happName'],
                        'cid' => $domain,
                        'subtitle' => $_POST['hpackageName'],
                        'versionname' => $_POST['hversion'],
                    );


                    $where['id'] = $res;
                    $where['fid'] = session('homeId');
                    if ($houzhui == 'ipa') {
                        //输出plist
                        $fp = fopen('./Public/appipa/' . $res . ".plist", "w+");
                        fwrite($fp, createplist($ctlist));
                        fclose($fp);

                        $plist = 'itms-services://?action=download-manifest&url=' . 'https://' . 'download.qq6789.com/' . $res . ".plist";

                        $model->where($where)->setField('plist', $plist);

                    } elseif ($houzhui == 'apk') {
                        $model->where($where)->setField('uptxt', $domain);
                    }
                    $shorturl = urlShort($res);
                    $date['web'] = "/a/$shorturl";
                    $date['shorturl'] = $shorturl;
                    $date['isgg'] = $result['isggconfig'];
                    $model->where($where)->save($date);
//                    $model->where($where)->setField('web', '/a/' . $shorturl);
//                    $model->where($where)->setField('shorturl', $shorturl);
//                    $model->where($where)->setField('isgg', $result['isggconfig']);
                    $member->where(array('id' => session('homeId')))->setInc('appnum', 1);


                    $data['status']  = 'success';
                    $data['id']  = $res;

                    $this->ajaxReturn($data,'JSON');
                    //  echo json_encode($data);
                } else {

                    $data['status'] = 'error';
                    $this->ajaxReturn($data);

                }
            }else{


                    //处理该上传文件
                    $ctlist = array(
                        'ssl_server' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
                        'bundle_identifier' => $_POST['hpackageName'],
                        'title' => $_POST['happName'],
                        'cid' => $domain,
                        'subtitle' => $_POST['hpackageName'],
                        'versionname' => $_POST['hversion'],
                    );

                unlink('./Public/appipa/' . $ss . '.plist');
                    $where['id'] = $ss;
                    $where['fid'] = session('homeId');
                    if ($houzhui == 'ipa') {
                        //输出plist
                        $fp = fopen('./Public/appipa/' . $ss . ".plist", "w+");
                        fwrite($fp, createplist($ctlist));
                        fclose($fp);

                        $plist = 'itms-services://?action=download-manifest&url=' . 'https://' . 'download.qq6789.com/' . $ss . ".plist";

                        $model->where($where)->setField('plist', $plist);

                    } elseif ($houzhui == 'apk') {
                        $model->where($where)->setField('uptxt', $domain);
                    }

                $shorturl = urlShort($ss);
                $date['web'] = "/a/$shorturl";
                $date['uptxt'] = $domain;
                $date['shorturl'] = $shorturl;
                $date['isgg'] = $result['isggconfig'];
                $date['zsize'] = $_POST['iAppSize'];
                $model->where($where)->save($date);

                    $shorturl = urlShort($ss);
                   // $model->where($where)->setField('web', '/a/' . $shorturl);
                  //  $model->where($where)->setField('shorturl', $shorturl);
                   // $model->where($where)->setField('zsize', $_POST['iAppSize']);
                  //  $model->where($where)->setField('isgg', $result['isggconfig']);
                    $member->where(array('id' => session('homeId')))->setInc('appnum', 1);


                    $data['status']  = 'success';
                    $data['id']  = $ss;

                    $this->ajaxReturn($data,'JSON');
                    //  echo json_encode($data);



            }


        }

    }


    public function upload()
    {

        $member = M('Member');
        $uptype = $member->where(array('id' => session('homeId')))->getField('uptype ');

        switch ($uptype) {
            //type:1 七牛 type:2本地  type:3远程
            case '1':
                $this->userqn();
                break;
            case '2':
                $this->userup();
                break;
            case '3':
                $this->userycup();
                break;
        }

    }

    public function userup()
    {

        if (!empty($_POST)) {


            $member = M('Member');
            $result = $member->where(array('id' => session('homeId')))->find();

            $uploadedsize = $_POST['iAppSize'] / 1024 / 1024;
            $member->where(array('id' => session('homeId')))->setInc('uploadedsize', round($uploadedsize, 2));

            $domain = trim($_POST['sDownLink']);
            $houzhui = trim($_POST['hext']);


            $model = M("List");

            $model->uptxt = $domain;
            $model->hslogo = $_POST['hslogo'];
            $model->nickname = $_POST['happName'];
            $model->create_time = time();
            $model->zsize = $_POST['iAppSize'];
            $model->fid = session('homeId');
            $model->ext = $houzhui;
            $model->needmoney = '1';
            if ($res = $model->where(array('id' => $_POST['iLocalId']))->save()) {
                //处理该上传文件
                $ctlist = array(
                    'ssl_server' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
                    'bundle_identifier' => $_POST['hpackageName'],
                    'title' => $_POST['happName'],
                    'cid' => $domain,
                    'subtitle' => $_POST['hpackageName'],
                    'versionname' => $_POST['hversion'],
                );


                $where['id'] = $_POST['iLocalId'];
                $where['fid'] = session('homeId');
                if ($houzhui == 'ipa') {
                    //输出plist
                    $fp = fopen('./Public/appipa/' . $_POST['iLocalId'] . ".plist", "w+");
                    fwrite($fp, createplist($ctlist));
                    fclose($fp);

                    $plist = 'itms-services://?action=download-manifest&url=' . 'https://' . 'download.qq6789.com/' . $_POST['iLocalId'] . ".plist";

                    $model->where($where)->setField('plist', $plist);

                } elseif ($houzhui == 'apk') {
                    $model->where($where)->setField('uptxt', $domain);
                }
                $shorturl = urlShort($_POST['iLocalId']);
                $model->where($where)->setField('web', '/a/' . $shorturl);
                $model->where($where)->setField('shorturl', $shorturl);
                $model->where($where)->setField('isgg', $result['isggconfig']);
                $member->where(array('id' => session('homeId')))->setInc('appnum', 1);

                $data['status'] = 'success';
                $data['id'] = $shorturl;
                $this->ajaxReturn($data);

            } else {

                $data['status'] = 'error';
                $this->ajaxReturn($data);

            }

        }
    }

    public function uploadbd()
    {
        //dd($_POST).'<br>';dd($_FILES).'<br>';die;

        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();


        //$upsize = $model-> where(array('fid'=>session('homeId')))->Sum('zsize');

        $config = array(
            'maxSize' => $result['singlesize'] * 1024 * 1024, // 附件上传大小
            'rootPath' => './Public/uploads/', // 附件上传根目录
            'savePath' => '',// 附件上传（子）目录
            'exts' => array('ipa', 'apk'),// 附件上传类型
        );
        $upload = new \Think\Upload($config);// 实例化上传类

        $info = $upload->uploadOne($_FILES['file']);

        if (!$info) {
            $data['error'] = $upload->getError();
        } else {

            $model = M("List");
            $model->uptxt = $info['savepath'] . $info['savename'];
            $model->create_time = time();
            $model->zsize = $info['size'];
            $name = explode('.', $info['name']);

            $model->fid = session('homeId');
            $model->ext = end(explode('.', $info['name']));
            $model->needmoney = '1';

            if ($tid = $model->add()) {
                $where['id']=$tid;
                $shorturl = urlShort($tid);
                $model->where($where)->setField('web', '/a/' . $shorturl);
                $model->where($where)->setField('shorturl', $shorturl);
                $model->where($where)->setField('isgg', $result['isggconfig']);
                $data['path'] = $info['savepath'] . $info['savename'];
                $data['id'] = $tid;
                $data['status'] = 'success';

                //dd($tid);
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 'error';
            }

        }
        $this->ajaxReturn($data, 'JSON');
    }


    public function add()
    {
        $tid = session("tid");
        $model = M("List");
        $where['id'] = $tid;
        $where['fid'] = session('homeId');
        $this->info = $model->where($where)->find();

        $this->display();
    }

    public function update()
    {
        //默认显示添加表单
        if (IS_POST) {

            $model = M("List");
            if (!$model->create()) {
                $this->error($model->getError());
            } else {

            }
        }
    }

    public function qrcode($text = 'http://xx.w6cc.com', $tid, $size = '4', $level = 'L', $padding = 2, $logo = true)
    {
        $path = './Public/png/';
        $QR = $path . $tid . '.png';
        vendor("Phpqrcode.phpqrcode");
        \QRcode::png($text, $QR, $level, $size, $padding);
        imagepng($QR);
        return $tid;
    }

    public function listinfo()
    {
        if (I('post.nickname') == "") {

            if (I('get.ext') == "") {
                $where['fid'] = session('homeId');
                //  $where['status'] = 0;
            } else {
                $where['fid'] = session('homeId');
                // $where['status'] = 0;
                $where['ext'] = I('get.ext');
            }

            $model = M('List');
        } else {
            $where['nickname'] = trim(I('nickname'));
            $where['fid'] = session('homeId');
            //   $where['status'] = 0;
            $model = M('List');
        }

        $num_my = 15;
        $count = $model->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Extend\Page($count, $num_my);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $list = $model->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->order('id DESC')->select();
        //dd($list);die;
        $dqy = I('get.p') ? I('get.p') : 1;
        $this->pp = $count - ($dqy - 1) * $num_my;
        $this->count = $count;

        //二維碼
        foreach ($list as $k => $val) {
            $list[$k]['qrcode'] = $this->qrcode('http://' . 'www.qq6789.com'. $val['web'], $val['id']);
        }
        $this->assign('list', $list);
        $this->assign('page', $show);
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
        $result['classon'] = 'class = "active"';
        $this->result = $result;
        $this->display();
    }

    public function hebing()
    {
        if (I('post.nickname') == "") {

            if (I('get.ext') == "") {
                $where['fid'] = session('homeId');
                $where['status'] = 0;
            } else {
                $where['fid'] = session('homeId');
                $where['status'] = 0;
                $where['ext'] = I('get.ext');
            }

            $model = M('List');
        } else {
            $where['nickname'] = trim(I('nickname'));
            $where['fid'] = session('homeId');
            $where['status'] = 0;
            $model = M('List');
        }

        $num_my = 20;
        $count = $model->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Extend\Page($count, $num_my);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $list = $model->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->order('id DESC')->select();
        //dd($list);die;
        $dqy = I('get.p') ? I('get.p') : 1;
        $this->pp = $count - ($dqy - 1) * $num_my;
        $this->count = $count;
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    public function yeshb()
    {
        if (I('post.nickname') == "") {

            if (I('get.ext') == "") {
                $where['fid'] = session('homeId');
                $where['status'] = 0;
            } else {
                $where['fid'] = session('homeId');
                $where['status'] = 0;
                $where['ext'] = I('get.ext');
            }

            $model = M('Newlist');
        } else {
            $where['nickname'] = trim(I('nickname'));
            $where['fid'] = session('homeId');
            $where['status'] = 0;
            $model = M('Newlist');
        }

        $num_my = 20;
        $count = $model->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Extend\Page($count, $num_my);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $list = $model->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->order('id DESC')->select();
        //dd($list);die;
        $dqy = I('get.p') ? I('get.p') : 1;
        $this->pp = $count - ($dqy - 1) * $num_my;
        $this->count = $count;
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    public function hblist()
    {

        $this->display();

    }

    public function hbcheck()
    {
        if (IS_POST) {

            if (!empty($_FILES['fileToUpload']['name'])) {

                $upload = new \Think\Upload();// 实例化上传类
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = './Public/icon/'; // 设置附件上传根目录
                // 上传单个文件
                $info = $upload->uploadOne($_FILES['fileToUpload']);
                if (!$info) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                } else {// 上传成功 获取上传文件信息

                    header('Content-type:text/html;charset=utf-8');
                    //读取图片文件，转换成base64编码格式
                    $image_file = $info['savepath'] . $info['savename'];
                    $_POST['newlogo'] = $image_file;
                }
            } else {
                $_POST['newlogo'] = '';
            }

            $tid_count = count($_POST['tid']);


            $_POST['tid'] = implode(',', $_POST['tid']);
            $_POST['tname'] = implode(',', array_slice($_POST['tname'], 0, $tid_count));
            $_POST['tweb'] = implode(',', array_slice($_POST['tweb'], 0, $tid_count));
            $_POST['fid'] = session('homeId');

            $model = M("Newlist");

            $_POST['lrtime'] = time();
            if (!$model->create()) {
                $this->error($model->getError());
            } else {

                if ($model->add()) {
                    $this->success("提交成功", U('index/yeshb'));
                } else {
                    $this->error("提交失败");
                }
            }
        }
    }

    public function hbupdate()
    {
        if (IS_POST) {
            $model = M("Newlist");
            if (!empty($_FILES['fileToUpload']['name'])) {

                $upload = new \Think\Upload();// 实例化上传类
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = './Public/icon/'; // 设置附件上传根目录
                // 上传单个文件
                $info = $upload->uploadOne($_FILES['fileToUpload']);
                if (!$info) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                } else {// 上传成功 获取上传文件信息

                    header('Content-type:text/html;charset=utf-8');
                    //读取图片文件，转换成base64编码格式
                    $image_file = $info['savepath'] . $info['savename'];
                    $_POST['newlogo'] = $image_file;
                }
            } else {
                $where['id'] = $_POST['id'];
                $newlogo = $model->where($where)->getField('newlogo');
                if (!empty($newlogo)) {
                    $_POST['newlogo'] = $newlogo;
                } else {
                    $_POST['newlogo'] = '';
                }

            }

            $tid_count = count($_POST['tid']);

            $_POST['tid'] = implode(',', $_POST['tid']);
            $_POST['tname'] = implode(',', array_slice($_POST['tname'], 0, $tid_count));
            $_POST['tweb'] = implode(',', array_slice($_POST['tweb'], 0, $tid_count));
            $_POST['fid'] = session('homeId');


            $_POST['lrtime'] = time();
            if (!$model->create()) {
                $this->error($model->getError());
            } else {

                if ($model->save()) {
                    $this->success("更新成功", U('index/yeshb'));
                } else {
                    $this->error("更新失败");
                }
            }
        }
    }

    public function delete($id)
    {
        $model = M('List');
        $map['id'] = $id;
        $map['fid'] = session('homeId');
        //$result = $model->where($map)->setInc('status',3);
        $zsize = $model->where($map)->getField('zsize');
        $result = $model->where($map)->delete();
        if ($result) {
            $data['id'] = session('homeId');
            M('member')->where($data)->setDec('appnum');
            M('member')->where($data)->setDec('uploadedsize', $zsize);

            //unlink('./Public/uploads/'.$info['uptxt']);
            unlink('./Public/appipa/' . $id . '.plist');
            $this->success("删除成功", U('index/listinfo'));
        } else {
            $this->error("删除失败");
        }
    }

    public function duodelete($id)
    {
        $model = M('Newlist');
        $map['id'] = $id;
        $map['fid'] = session('homeId');
        //$result = $model->where($map)->setInc('status',3);
        //$info = $model->where($map)->find();
        $result = $model->where($map)->delete();
        if ($result) {
            //unlink('./Public/uploads/'.$info['uptxt']);
            //unlink('./Public/appipa/'.$id.'.plist');
            $this->success("删除成功", U('index/yeshb'));
        } else {
            $this->error("删除失败");
        }
    }

    public function modify($id)
    {
        $model = M("List");
        $where['id'] = $id;
        $where['fid'] = session('homeId');
        $info = $model->where($where)->find();
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
        $this->result = $result;
        $this->info = $info;
        $this->datadd = $info[""];
		    $this->assign('loginuid', session('homeId'));
        $this->display();
    }

    public function newmodify($id)
    {
        $model = M("Newlist");
        $where['id'] = $id;
        $where['fid'] = session('homeId');
        $info = $model->where($where)->find();

        $tid = explode(',', $info['tid']);
        $tname = explode(',', $info['tname']);
        $tweb = explode(',', $info['tweb']);


        $this->tid = $tid;
        $this->tname = $tname;
        $this->tweb = $tweb;
        $this->info = $info;
		$this->assign('loginuid', session('homeId'));
        $this->display();
    }

    public function updateinfo()
    {
        //默认显示添加表单
        if (IS_POST) {

            if (!empty($_FILES['fileToUpload']['name'])) {
                $id = I('id');
                $list = M("List")->where("id = $id")->find();
                $upload = new \Think\Upload();// 实例化上传类
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath = './Public/icon/'; // 设置附件上传根目录
                // 上传单个文件
                $info = $upload->uploadOne($_FILES['fileToUpload']);
                if (!$info) {// 上传错误提示错误信息
                    $this->error($upload->getError());
                } else {// 上传成功 获取上传文件信息

                    header('Content-type:text/html;charset=utf-8');
                    //读取图片文件，转换成base64编码格式
                    $image_file = $info['savepath'] . $info['savename'];
                    $_POST['zxlogo'] = $image_file;
                }
            } else {
                //$_POST['zxlogo'] = '';
            }

            if (!$_POST['nickname']) {
                $this->error('APP名必须填！');
            }

			if($_POST['ext']=='ipa' &&!$_POST['BundleID'] )
			{
				$this->error('Bundle ID必须填！');
			}

            $shorturl = $_POST['shorturl'];
            $data['shorturl'] = $shorturl;
            $_POST['web']="/a/$shorturl";
            $where['id'] = $_POST['id'];
            $model = M("List");
            $copy  =$model->where($where)->find();
            $list = $model->where($data)->find();

            if($list&&$list['id']!=$copy['id']){
             $this->error('下载地址重复请从新输入');
            }

            if (!$model->create()) {
                $this->error($model->getError());
            } else {

                if ($model->save()!==false) {
                    if ($_POST['zxlogo']) {
                        //删除原来图片 节省服务内存空间
                        unlink('./Public/icon/' . $list['zxlogo']);
                    }
                    $mmarr = M('List')->where(array('id' => $_POST['id']))->find();
                    //前期只能先这样或许ipa的下载信息了.
                    if ($mmarr['ext'] == 'ipa') {

                        $ctlist = array(
                            'ssl_server' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
                            //'bundle_identifier' => $_POST['BundleID'],
                            'bundle_identifier' => $mmarr['iphonebundleid'],
                            'title' => $mmarr['nickname'],
                            'cid' => $mmarr['uptxt'],
                            'subtitle' => $mmarr['nickname'],
                            'versionname' => $mmarr['bundleversion'],
							              'icon' => 'https://download.qq6789.com'.'/Public/icon/' . $mmarr['zxlogo'],
                        );

                        $where['id'] = $mmarr['id'];
                        $where['fid'] = session('homeId');
                        //输出plist
                        $fp = fopen('./Public/appipa/' . $mmarr['id'] . ".plist", "w+");
                        fwrite($fp, createplist($ctlist));
                        fclose($fp);

                        $plist = 'itms-services://?action=download-manifest&url=' . 'https://' . 'download.qq6789.com/' . $mmarr['id'] . ".plist";

                        $model->where($where)->setField('plist', $plist);

                    }


                    if ($mmarr['isgg'] == '2') {
                        $ctlist = array(
                            'ssl_server' => 'http://' . $_SERVER['SERVER_NAME'] . '/',
                            //'bundle_identifier' => $_POST['BundleID'],
                            'bundle_identifier' => $mmarr['iphonebundleid'],
                            'title' => $mmarr['nickname'],
                            'cid' => $mmarr['uptxt'],
                            'subtitle' => $mmarr['nickname'],
                            'versionname' => $mmarr['bundleversion'],
							              'icon' => 'https://download.qq6789.com'.'/Public/icon/' . $mmarr['zxlogo'],
                        );


                        $where['id'] = $mmarr['id'];
                        $where['fid'] = session('homeId');
                        if ($mmarr['ext'] == 'ipa') {
                            //输出plist
                            $fp = fopen('./Public/appipa/' . $mmarr['id'] . ".plist", "w+");
                            fwrite($fp, createplist($ctlist));
                            fclose($fp);

                            $plist = 'itms-services://?action=download-manifest&url=' . 'https://' . 'download.qq6789.com/' . $mmarr['id'] . ".plist";

                            $model->where($where)->setField('plist', $plist);

                        }

                    }
                    $this->success("提交成功", U('index/listinfo'));
                } else {
                    $this->error("提交失败");
                }
            }
        }
    }

    /**
     * 批量删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function alldel()
    {

        if (IS_POST) {
            $hobby = $_POST['hobby'];
            if (empty($hobby)) {
                $this->error("不能提交空值!");
            }
            $member = M("Member");
            $result = $member->where(array('id' => session('homeId')))->find();

            $post = M('List');
            $ii = 0;
            foreach ($hobby as $k => $val) {


                $map['status'] = 0;
                $map['id'] = $val;
                $map['fid'] = session('homeId');
                $res = $post->where($map)->delete();
                unlink('./Public/appipa/' . $val . '.plist');

                /**
                 * if ($result['uptype'] == 1) {
                 * // 初始化签权对象
                 * $auth = new \Qiniu\Auth(trim($result['accesskey']), trim($result['secretkey']));
                 *
                 * //初始化BucketManager
                 * $bucketMgr = new \Qiniu\Storage\BucketManager($auth);
                 * $err = $bucketMgr->delete(trim($result['bucket']), trim($result['qnname']));
                 * }
                 **/

                if ($result['uptype'] == 2) {
                    $uptxt = $post->where(array('id' => $val))->getField('uptxt');
                    unlink($uptxt);
                }

                $ii++;
            }
            if ($res) {
                $member->where(array('id' => session('homeId')))->setDec('appnum', $ii);
                //unlink('./Public/uploads/'.$info['uptxt']);
                $this->success("批量删除成功", U('Index/listinfo'));
            } else {
                $this->error("删除失败");
            }

        } else {
            $this->error("请不要恶意提交");
        }
    }

    /**
     * 批量删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delnewall()
    {

        if (IS_POST) {

            $hobby = $_POST['hobby'];
            if (empty($hobby)) {
                $this->error("不能提交空值!");
            }
            $member = M("Member");
            $result = $member->where(array('id' => session('homeId')))->find();

            $post = M('Newlist');
            foreach ($hobby as $k => $val) {

                $map['id'] = $val;
                $map['fid'] = session('homeId');
                $res = $post->where($map)->delete();

            }
            if ($res) {
                $this->success("批量删除成功", U('Index/yeshb'));
            } else {
                $this->error("删除失败");
            }

        } else {
            $this->error("请不要恶意提交");
        }
    }

    public function kongbai()
    {
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
		$this->assign('loginuid', session('homeId'));
        if ($result['uptype'] == 1 && $result['accesskey'] == '' && $result['secretkey'] == '') {

            $this->success("当前为七牛上传，请设置七牛信息...", U('Member/jiekou'), 3);

        } else {
            $this->result = $result;
            $this->display();
        }
    }


    public function appinfo($id)
    {
        $model = M("List");
        $where['id'] = $id;
        $where['fid'] = session('homeId');
        $info = $model->where($where)->find();
        $this->info = $info;
        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $result['downnum'] =$result['downnum']+$result['autodailygiftnum'];
        $this->result = $result;
        $downhistory = M("Downhistory");
        $nowtime = time();
        $weekarr = array();
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 6);
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 5);
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 4);
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 3);
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 2);
        $weekarr[] = date('Y-m-d', $nowtime - 3600 * 24 * 1);
        $weekarr[] = date('Y-m-d', $nowtime);
        $weekstr = '';
        $liulanstr = '';
        $downstr = '';
        foreach ($weekarr as $val) {
            $weekstr .= "'" . $val . "',";
            $starttime = $val . ' 00:00:00';
            $endtime = $val . ' 23:59:59';
            $hisarrnum = $downhistory->where("appid='" . $id . "' and addtime>'" . $starttime . "' and addtime<'" . $endtime . "' and type=0 ")->count();
            $liulanstr .= "" . $hisarrnum . ",";
            $hisarrnum = $downhistory->where("appid='" . $id . "' and addtime>'" . $starttime . "' and addtime<'" . $endtime . "' and type=1 ")->count();
            $downstr .= "" . $hisarrnum . ",";
        }
        $this->assign('weekstr', rtrim($weekstr, ','));
        $this->assign('liulanstr', rtrim($liulanstr, ','));
        $this->assign('downstr', rtrim($downstr, ','));
        $this->display();
    }

    /**
     * 查询合并
     * @param $id 软件编号id
     */
    public function myhebing($id)
    {
        //实例化
        $model = M("List");
        //根据参数存入数组
        $where['id'] = $id;
        // 用户session
        $where['fid'] = session('homeId');
        //查询
        $info = $model->where($where)->find();
        //返回前台
        $this->info = $info;
        //查询出 属于当前用户 并且不等于 当前id 的数据
        $where['id'] = array('neq', $id);
        $where['ext'] = array('neq', $info['ext']);
        $list = $model->where($where)->order('id DESC')->select();
        //销毁不需要的变量释放内存
        unset($where);

        $hebing = M("Hebing");
        //创建一个新的数组
        $where = array();

        $where['appid'] = $id;
        $where['fid'] = session('homeId');
//        $apparr = $hebing->where($where)->select();
        $apparr = $hebing->where($where)->find();
        $toid['id'] = $apparr['toaddid'];
        if ($apparr) {

        }
        $listtow = M('List')->where($toid)->find();
        $this->listtow = $listtow;
        $hebingedarr = array();
        $hebingedarr[] = $apparr['toaddid'];
//		foreach($apparr as $val){
//			$hebingedarr[] = $val['toaddid'];
//		}

        foreach ($list as $k => $val) {
            if (in_array($val['id'], $hebingedarr)) {
                $list[$k]['checkstr'] = ' checked="checked" ';
            } else {
                $list[$k]['checkstr'] = '';
            }
        }
        $this->assign('list', $list);
        $this->assign('hebingedarr', $hebingedarr);

        $this->display();
    }

    public function myhebing_act()
    {

        if (IS_POST) {
            $hebing = M("Hebing");
            $hobby = $_POST['hobby'];
            $appid = (int)$_POST['appid'];
            if (empty($hobby)) {

                $map = array();
                $map['appid'] = $appid;
                $map['fid'] = session('homeId');
                $res = $hebing->where($map)->delete();

                $map = array();
                $map['toaddid'] = $appid;
                $map['fid'] = session('homeId');
                $res = $hebing->where($map)->delete();

                $this->success("取消合并成功", U('Index/myhebing', array('id' => $appid)));
            } else {

                $member = M("Member");
                $result = $member->where(array('id' => session('homeId')))->find();

                $map['appid'] = $hobby[0];
                $map['fid'] = session('homeId');
                $ho = $hebing->where($map)->select();
                if (!empty($ho)) {
                    $this->error("选择合并的应用已和其他应用合并请先解除");
                }

                $post = M('List');
                $ii = 0;
                if (count($hobby) > 1) {

                    $this->error("只能选择一个应用进行合并!");
                }

                foreach ($hobby as $k => $val) {

                    $map = array();
                    $map['appid'] = $appid;
                    $map['toaddid'] = $val;
                    $map['fid'] = session('homeId');
                    $res = $hebing->where($map)->delete();

                    $map = array();
                    $map['appid'] = $val;
                    $map['toaddid'] = $appid;
                    $map['fid'] = session('homeId');
                    $res = $hebing->where($map)->delete();

                    $data = array();
                    $data['appid'] = $appid;
                    $data['toaddid'] = $val;
                    $data['fid'] = session('homeId');
                    $hebing->add($data);

                    $data = array();
                    $data['appid'] = $val;
                    $data['toaddid'] = $appid;
                    $data['fid'] = session('homeId');
                    $hebing->add($data);
                    $ii++;
                }
                $this->success("合并成功", U('Index/myhebing', array('id' => $appid)));
            }

        } else {
            $this->error("请不要恶意提交");
        }
    }

    public function down($id)
    {
        $model = M("List");
        $where['id'] = $id;
        $info = $model->where($where)->find();
        $this->info = $info;
        if($info['status']!=0)
        {
            $this->error("已下架！");
        }
        $res = $model->where(array('id' => $info['id']))->setInc('xznum', '1');

        $downhistory = M("Downhistory");
        $nowtime = time();
        $data = array();
        $data['appid'] = $info['id'];
        $data['addtime'] = date('Y-m-d H:i:s', $nowtime);
        $data['type'] = '1';
        $downhistory->add($data);
        $url = '';
        $uptype = M("Member")->where(array('id' => $info['fid']))->getField('uptype');
        $candownloadnums = M("Member")->where(array('id' => $info['fid']))->getField('downnum');
        $autodailygiftnum = M("Member")->where(array('id' => $info['fid']))->getField('autodailygiftnum');//每日自动赠送的
        if ($info['ext'] == 'ipa') {
            $url = $info['plist'];
        } else {
            if ($uptype == '1') {
                $url = trim($info['uptxt']);

                $mmtime = dechex(time() + 500);
                $pathurl = parse_url($url);
                $str = '96884e98998a609a2bb836a8e8b84dbbd08bdbaa' . $pathurl['path'] . $mmtime;
                $sign = strtolower(md5($str));
                $url = $url . '?sign=' . $sign . '&t=' . $mmtime;

            } elseif ($uptype == '2') {
                $url = trim($info['uptxt']);
				        //$url = __PUBLIC__ . '/uploads/' . $info['uptxt'];
                $mmtime = dechex(time() + 500);
                $pathurl = parse_url($url);
                $str = '96884e98998a609a2bb836a8e8b84dbbd08bdbaa' . $pathurl['path'] . $mmtime;
                $sign = strtolower(md5($str));
                $url = $url . '?sign=' . $sign . '&t=' . $mmtime;
            }
        }

        // 2017/7/31 add
        $appsize = formatBytesMb($info['zsize']);
        $neednum = 1;
        $config = M("Config")->find();
        $filesizearr = explode(',', $config['filesizearr']);
        $downnumarr = explode(',', $config['downnumarr']);
        foreach ($filesizearr as $k => $val) {
            if ($appsize > $val) {
                $neednum = $downnumarr[$k];
            }
        }
        //$mmsid = session('homeId');
        $userarr = M("Member")->where(array('id' => $info['fid']))->find();
        if($candownloadnums + $autodailygiftnum<=0)
        {
          $this->error("下载次数不足！");
          exit;
        }
        //added by cq qq:852986690
        if($autodailygiftnum>0) //优先从每日赠送的里面扣
        {
          M("Member")->where(array('id' => $info['fid']))->setField('autodailygiftnum',$autodailygiftnum-$neednum);
        }else {
          M("Member")->where(array('id' => $info['fid']))->setField('downnum',$candownloadnums-$neednum);
        }

      //  if ($info['needmoney']) {
      //      //$result = M('Member')->where(array('id'=>session('homeId')))->find();
      //      $payedcount = M("taocanorder")->where(array('userid' => session('homeId'), 'listid' => $info['id'], 'status' => '1'))->count();
      //      if (!$payedcount) {
      //          if (!$userarr['everydaynum']) {
      //              if ($userarr['downnum'] < $neednum) {
      //                  $this->error("下载次数不足！");
      //                  exit;
      //              }
      //              $res22 = M("Member")->where(array('id' => $info['fid']))->setDec('downnum', $neednum);
      //          } else {
      //              $res22 = M("Member")->where(array('id' => $info['fid']))->setDec('everydaynum', $neednum);
      //          }
      //      }
      //  }
        //===end
        header('HTTP/1.1 301 Moved Permanently');
        //if ($info['ext'] == 'apk') {
        header('Location: ' . $url);
      //  }
//        $this->redirect("Appipa/downloading/id/$id/");
//          $this->display('Appipa/downloading');
        // readfile('Appipa/downloading');
        exit;

    }

    //修改手机号
    public function modifyphone()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {
            $checkcode = I('checkcode88');
            $config = M("Config")->find();

            $phone = I('phone');

            if (strlen($phone) != 11) {
                $this->error('请输入正确的手机号码！');
            }
            if ($checkcode != session('emailcode88')) {
                $this->error('验证码不正确！');
            }
            if ($phone != session('emailadd88')) {
                $this->error('手机号码不正确！');
            }

            //验证账号密码是否正确
            $user = M("Member")->where(array('phone' => $phone))->find();

            if ($user) {
                $this->error('此手机号码已存在！');
            }
            $data = array();
            $data['phone'] = $phone;
            $tid = M("Member")->where(array("id" => session('homeId')))->save($data);

            $this->success("手机号修改成功", U('member/index'));
        }
    }

    //修改邮箱
    public function modifymail()
    {
        if (!IS_POST) $this->error("非法请求");
        //默认显示添加表单

        if (IS_POST) {
            $checkcode = I('checkcode');
            $config = M("Config")->find();

            $username = I('username');
            if (!$username) {
                $this->error('邮箱不正确！');
            }
            if (strlen($username) > 25) {
                $this->error('此邮箱太长，请从新换一个邮箱！');
            }
            if ($checkcode != session('emailcode')) {
                $this->error('验证码不正确！');
            }
            if ($username != session('emailadd')) {
                $this->error('邮箱不正确！');
            }

            //验证账号密码是否正确
            $user = M("Member")->where(array('username' => $username))->find();

            if ($user) {
                $this->error('此邮箱已存在！');
            }
            $data = array();
            $data['username'] = $username;
            $tid = M("Member")->where(array("id" => session('homeId')))->save($data);

            $this->success("邮箱修改成功", U('member/index'));
        }
    }

    public function uploadFile()
    {
        //dd($_POST).'<br>';dd($_FILES).'<br>';die;

        $member = M('Member');
        $result = $member->where(array('id' => session('homeId')))->find();
        $this->result = $result;

        $config = array(
            'maxSize' => 20 * 1024 * 1024, // 附件上传大小
            'rootPath' => './Public/uploads/', // 附件上传根目录
            'savePath' => '',// 附件上传（子）目录
            'exts' => array('jpeg', 'jpg', 'gif', 'png', 'bmp', 'txt', 'rar', 'zip', 'doc', 'docx', 'ini', 'conf', 'eml', 'pdf', 'xsl', 'xslx', 'ppt', 'pptx'),// 附件上传类型
        );

        $upload = new \Think\Upload($config);// 实例化上传类

        $info = $upload->uploadOne($_FILES['qqfile']);
        $key = date('YmdHis', time()) . rand(1000, 9999);
        if (!$info) {
            $data['error'] = $upload->getError();
        } else {

            $filename = '/Public/uploads/' . $info['savepath'] . $info['savename'];
            $data['success'] = true;
            $data['key'] = $key;
            $data['name'] = $info['savename'];
            $temparr = explode('.', $info['savename']);
            $ext = end($temparr);
            if (in_array($ext, array('jpeg', 'jpg', 'gif', 'png', 'bmp'))) {
                $data['img'] = $filename;
            }
            $this->ajaxReturn($data);

        }
        $this->ajaxReturn($data, 'JSON');
    }

    public function uploadftp()
    {

        $name = $_POST['name'];

        $data['name'] = $name;

        $ftp_server = "123.56.223.187";
        $ftp_user_name = "download";
        $ftp_user_pass = "download";
        $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
        $file = './Public/uploads/' . $name;
        $mmfilenamearr = explode('/', $name);
        $mmfilename = end($mmfilenamearr);
        $remote_file = '/public_html/upload/' . $mmfilename; // 注意：这里的"/test"指的是ftp根目录下的test文件夹，而非系统跟目录下的test
        $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

        if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
            $data['name'] = 'ok';
        } else {
            $data['name'] = 'error';
        }
        ftp_close($conn_id);


        $this->ajaxReturn($data);

        $this->ajaxReturn($data, 'JSON');
    }

    /**
     * 还原
     * @param $id  post id
     * @param $status  操作函数
     */
    public function huany($id)
    {

        $status = I('status');
        $model = M('List');
        $map['status'] = array('in', '0,1,2,3');
        $map['id'] = $id;
        if ($status == 3) {
            $result = $model->where($map)->setDec('status', 3);
            //$result = $model->where("id=".$id)->delete();
            if ($result) {
                $this->success("上架成功", U('Index/listinfo'));
            } else {
                $this->error("上架失败");
            }
        } else {
            $this->error("参数错误");
        }

    }
}
